import {reqGetCode,reqUserRegister,reqUserLogin,reqUserInfo,reqLogout} from '@/api'
import { setToken, removeToken, getToken } from '@/utils/token';
const state = {
    code:'',
    token:getToken(),
    userInfo:{}
}
const mutations = {
    GETCODE(state,code){
        state.code = code;
    },
    USERLOGIN(state,token){
        state.token = token;
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo;
    },
    CLEAR(state){
        state.userInfo = {};
        state.token = '';
        removeToken();
    },
}
const actions = { 
    async getCode({commit},phone){
        let result = await reqGetCode(phone);
        if(result.code === 200){
            commit('GETCODE',result.data);
            return 'ok'
        }else{
            return Promise.reject(new Error('error'))
        }
    },
    //注册
    async userRegister({commit},user){
        let result = await reqUserRegister(user);
        console.log(result);
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('该账号已注册'))
        }
    },
    //登录
    async userLogin({commit},user){
        let result = await reqUserLogin(user);
        if(result.code === 200){
            commit('USERLOGIN',result.data.token)
            setToken(result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('账号或密码错误'))
        }
    },
    //获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo();
        // console.log(result);
        if(result.code === 200){
            commit('GETUSERINFO',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('登录失败'))
        }
    },
    //退出登录
    async userLogout({commit}){
        let result = await reqLogout();
        // console.log(result);
        if(result.code === 200){
            commit('CLEAR')
            return 'ok'
        }else{
            return Promise.reject(new Error('退出登录失败'))
        }
    },
}
const getters = {
    
}
export default {
    state,
    mutations,
    actions,
    getters
}